using System.Linq;
using MvcSoft.Models;
using MvcSoft.Db;
using System;
using Microsoft.EntityFrameworkCore;

namespace MvcSoft.Repository
{
    public class EfRepository<T> : IRepository<T>where T:BaseEntity
    {
        private readonly ProductDb _db;
        private readonly DbSet<T> _table;

        public EfRepository()
        {
            _db =new ProductDb();
            _table =_db.Set<T>();
        }

        public IQueryable<T> Table
        {
            get
            {
                return _table.AsQueryable();
            }
        }
        public void Delete(int id)
        {
            var table=_table.Where(x=>x.Id==id).FirstOrDefault();
            table.IsDeleted=true;
            table.UpdatedTime=DateTime.Now;
            _table.Update(table);
            _db.SaveChanges();
        }

        public void Insert(T entity)
        {
            entity.IsActived=true;
            entity.IsDeleted=false;
            entity.CreatedTime=DateTime.Now;
            entity.UpdatedTime=DateTime.Now;
            entity.DisplayOrder=0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public void Update(T entity)
        {
            entity.UpdatedTime=DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
    }
}